<?php

namespace app\admin\controller;

use app\common\controller\BaseAdmin;
use app\admin\model\Balance as Model;
use app\admin\model\User as UserModel;

class Balance  extends BaseAdmin
{

   //需要获取的列表自定义字段内容，内容模型内定义
   protected $searchField =  [
       'user'=>['name','phone','money'=>'user_balance'],
       'action_text'
   ];

    /**
     * 初始化CURD控制器
     * @return void
     */
    public function initialize(){
        parent::initialize();
        $this->model = new Model();
    }




    /**
     * 列表Assign设置
     * 向index方法传模板页面参数
     */
    protected function indexAssign($data){
        $this->assign('dateList',Model::$ACTION);
    }


    /**
     * 编辑Assign设置
     * 向edit方法传模板页面参数
     */
    protected function editAssign($data){
        $this->assign('actionList',Model::$ACTION);
    }

    /**
     * 流水校对修复
     * @return void
     */
    public function repair(){
        $id = $this->request->param('id');
        while ($id){
            //修复的当前流水的前面一个流水
            $now = $this->model->where('id',$id)->find();
            $before = $this->model->where('user_id',$now->user_id)->where('id','<',$id)->order('id','desc')->find();
            if($before->balance == $now->before_amount){
                $this->error('当前数据是正常的无需修复');
            }else{
                $now->before_amount = $before->balance;
                if ($now->symbol == '-') {
                    $now->balance = $now->before_amount - $now->amount;
                } else {
                    $now->balance = $now->before_amount + $now->amount;
                }
                $now->save();

                //修复后面的流水
                $id = $this->model->where('user_id',$now->user_id)->where('id','>',$id)->order('id','asc')->value('id');
            }
        }
        $this->success('修复成功');
    }

    /**
     * 余额校对
     */
    public function check(){
        $id = $this->request->param('id');
        $model = $this->model->where('id', $id)->find();
        $user = UserModel::where('id', $model->user_id)->find();
        if ($user->money == $model->balance){
            $this->error('数据正常,无需校对');
        }else{
            $user->money = $model->balance;
            $user->save();
            $this->success('校对成功');
        }
    }
}